package com.dianrui.agent.activity;

import android.content.Intent;
import android.support.design.widget.BottomSheetDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dianrui.agent.R;
import com.dianrui.agent.adapter.MessageListAdapter;
import com.dianrui.agent.bean.MsgList;
import com.dianrui.agent.event.MsgListRfresh;
import com.dianrui.agent.event.RfreshMy;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.dianrui.agent.view.pulltoRefresh.PullToRefreshBase;
import com.dianrui.agent.view.pulltoRefresh.PullToRefreshListView;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MessageActivity extends BaseActivity {
    private List<MsgList>msgLists=new ArrayList<>();
    private int pageIndex=1;
    private MessageListAdapter adapter;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.msg_listview)
    PullToRefreshListView msgList;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;


    @Override
    public int getContentViewId() {
        return R.layout.message_list;
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        title.setText("我的消息");
        adapter=new MessageListAdapter(MessageActivity.this,msgLists);
        msgList.setAdapter(adapter);
        getMsgList(false);
        msgList.setMode(PullToRefreshBase.Mode.BOTH);
        msgList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getMsgList(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex++;
                getMsgList(false);

            }
        });
        adapter.setOnButtonClickListener(new MessageListAdapter.MessageClickListener() {
            @Override
            public void onMessagerDelete(final String msgId) {
                final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(MessageActivity.this);
                View view = LayoutInflater.from(MessageActivity.this).inflate(R.layout.msg_optation, null);
                LinearLayout deleteMsgLayout =view.findViewById(R.id.delete_msg_layout);
                deleteMsgLayout .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                        DelMsg(msgId);

                    }
                });
                LinearLayout cancel=view.findViewById(R.id.cancel_layout);
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                    }
                });
                bottomSheetDialog.setContentView(view);
                bottomSheetDialog.setCanceledOnTouchOutside(false);
                bottomSheetDialog.show();

            }

            @Override
            public void onMessageRead(String msgId, TextView title, TextView createtime, TextView contents, TextView show_reddot) {
                EventBus.getDefault().post(new RfreshMy());
                title.setTextColor(getResources().getColor(R.color.gray));
                createtime.setTextColor(getResources().getColor(R.color.gray));
                contents.setTextColor(getResources().getColor(R.color.gray));
                show_reddot.setVisibility(View.GONE);//已读的不显示红点
                startActivity(new Intent(MessageActivity.this,MessageDetails.class).putExtra("id", msgId));
            }


        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MsgListRfresh msgListRfresh) {
        getMsgList(true);
    }

    private void getMsgList(final boolean isRfresh) {
        if (isRfresh) {
            pageIndex=1;
        }
        JsonObject msgListJson=new JsonObject();
        msgListJson.addProperty("p",pageIndex);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl()+Url.MSG_LIST, msgListJson.toString(),  new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                msgList.onRefreshComplete();
                if (isRfresh) {
                   msgLists.clear();
                }
                if (!StringUtils.isEmpty(result)&&!isFinishing()) {
                    try {
                        JSONObject jsonObject=new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            JSONArray data=jsonObject.optJSONArray("data");
                            if (data.length()>0) {
                                for (int i = 0; i <data.length() ; i++) {
                                    MsgList msgList=new MsgList();
                                    msgList.messages_id=data.optJSONObject(i).optString("messages_id");
                                    msgList.title=data.optJSONObject(i).optString("title");
                                    msgList.contents=data.optJSONObject(i).optString("contents");
                                    msgList.create_time=data.optJSONObject(i).optString("create_time");
                                    msgList.is_read=data.optJSONObject(i).optString("is_read");
                                    msgList.send_time=data.optJSONObject(i).optString("send_time");
                                    msgLists.add(msgList);
                                }
                                if (adapter != null) {
                                    adapter.refresh(msgLists);
                                }


                            }

                        }else if ("1001".equals(jsonObject.optString("status"))){
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }else if ("1002".equals(jsonObject.optString("status")))  {
                            ToastUtil.showToast(jsonObject.optString("message"));
                            SharedUtil.setToken("");
                            SharedUtil.setAreaid("");
                            spUtils.clear();
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (msgLists.size()<=0) {
                    emptyView.setVisibility(View.VISIBLE);
                   msgList.setVisibility(View.GONE);
                }else {
                    emptyView.setVisibility(View.GONE);
                   msgList.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void DelMsg(String msg_id) {
        JsonObject msgListJson=new JsonObject();
        msgListJson.addProperty("admin_id",spUtils.getString("admin_id"));
        msgListJson.addProperty("messages_id",msg_id);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl()+Url.DELMESSAGE, msgListJson.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                msgList.onRefreshComplete();
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject=new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            getMsgList(true);
                            EventBus.getDefault().post(new RfreshMy());
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }else if ("1001".equals(jsonObject.optString("status"))){
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }else if ("1002".equals(jsonObject.optString("status")))  {
                            ToastUtil.showToast(jsonObject.optString("message"));
                            SharedUtil.setToken("");
                            spUtils.clear();
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @OnClick(R.id.back)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
